import os
import json
import random
import uuid
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename

# 配置
app = Flask(__name__,
            template_folder="../static/html",  # 确保模板文件夹路径正确
            static_folder="../static")  # 确保静态文件夹路径正确

# 上传配置
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024  # 限制5MB
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
# 明确指定上传路径（使用绝对路径更可靠）
app.config['UPLOAD_PATH'] = os.path.abspath(os.path.join(app.static_folder, 'img'))

# 持久化存储路径
DATA_FILE = "lottery_data.json"

# 确保上传目录存在（关键修复）
try:
    os.makedirs(app.config['UPLOAD_PATH'], exist_ok=True)
    print(f"上传目录已确认: {app.config['UPLOAD_PATH']}")  # 调试信息
except Exception as e:
    print(f"创建上传目录失败: {e}")


def load_data():
    """加载参与者数据"""
    default_data = {
        "userList": [
        ],
        "lastWinner": None
    }
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"加载数据失败: {e}")
    return default_data


def save_data(data):
    """保存数据"""
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存数据失败: {e}")
        return False


def allowed_file(filename):
    """检查文件格式是否允许"""
    return '.' in filename and \
        os.path.splitext(filename)[1].lower() in app.config['UPLOAD_EXTENSIONS']


def generate_unique_filename(filename):
    """生成唯一文件名，避免冲突"""
    ext = os.path.splitext(filename)[1].lower()
    return f"{uuid.uuid4().hex}{ext}"


@app.route('/')
def index():
    data = load_data()
    return render_template("lottery.html", user=data["lastWinner"])


@app.route("/begin", methods=['GET', 'POST'])
def begin():
    data = load_data()
    if not data["userList"]:
        return jsonify({"success": False, "message": "没有参与者"}), 400
    user = random.choice(data["userList"])
    data["lastWinner"] = user
    save_data(data)
    return jsonify(user)


@app.route("/list")
def list_participants():
    data = load_data()
    return jsonify(data["userList"])


@app.route("/add", methods=['POST'])
def add_participant():
    try:
        data = load_data()
        name = request.form.get('name', '').strip()

        # 验证姓名（省略...）

        # 核心修复：通过images[]获取所有上传的图片
        image_files = request.files.getlist('images[]')
        image_names = []

        for file in image_files:
            if file.filename == '':  # 跳过空文件
                continue
            if file and allowed_file(file.filename):
                # 生成唯一文件名
                filename = generate_unique_filename(secure_filename(file.filename))
                file_path = os.path.join(app.config['UPLOAD_PATH'], filename)

                # 保存文件
                try:
                    file.save(file_path)
                    image_names.append(filename)
                    print(f"图片保存成功: {file_path}")
                except Exception as e:
                    return jsonify({"success": False, "message": f"保存图片失败: {str(e)}"}), 500

        # 创建新参与者
        new_participant = {
            "name": name,
            "imgurl": ",".join(image_names) if image_names else ""
        }
        data["userList"].append(new_participant)

        if save_data(data):
            return jsonify({
                "success": True,
                "message": "添加成功",
                "participant": new_participant
            })
        else:
            return jsonify({"success": False, "message": "保存数据失败"}), 500

    except Exception as e:
        return jsonify({"success": False, "message": f"服务器错误: {str(e)}"}), 500


@app.route("/remove/<name>", methods=['DELETE'])
def remove_participant(name):
    try:
        data = load_data()
        participant = next((p for p in data["userList"] if p["name"] == name), None)
        if not participant:
            return jsonify({"success": False, "message": "未找到参与者"}), 404

        # 删除图片
        if participant.get("imgurl"):
            for img_name in participant["imgurl"].split(','):
                if img_name.strip():
                    img_path = os.path.join(app.config['UPLOAD_PATH'], img_name.strip())
                    if os.path.exists(img_path):
                        try:
                            os.remove(img_path)
                            print(f"删除图片: {img_path}")
                        except Exception as e:
                            print(f"删除图片失败: {e}")

        # 移除参与者
        data["userList"] = [p for p in data["userList"] if p["name"] != name]
        if data["lastWinner"] and data["lastWinner"]["name"] == name:
            data["lastWinner"] = None

        if save_data(data):
            return jsonify({"success": True, "message": "删除成功"})
        else:
            return jsonify({"success": False, "message": "保存数据失败"}), 500

    except Exception as e:
        return jsonify({"success": False, "message": f"服务器错误: {str(e)}"}), 500


@app.route("/update/<name>", methods=['PUT'])
def update_participant(name):
    try:
        data = load_data()
        idx = next((i for i, p in enumerate(data["userList"]) if p["name"] == name), None)
        if idx is None:
            return jsonify({"success": False, "message": "未找到参与者"}), 404

        new_name = request.form.get('name', '').strip()
        if not new_name:
            return jsonify({"success": False, "message": "姓名不能为空"}), 400
        if any(p["name"] == new_name and p["name"] != name for p in data["userList"]):
            return jsonify({"success": False, "message": "姓名已被使用"}), 400

        # 处理新图片
        image_files = request.files.getlist('images[0]') or request.files.getlist('images[]')
        new_images = []
        for file in image_files:
            if file.filename and allowed_file(file.filename):
                filename = generate_unique_filename(secure_filename(file.filename))
                file_path = os.path.join(app.config['UPLOAD_PATH'], filename)
                file.save(file_path)
                new_images.append(filename)

        # 保留旧图片
        keep_old = request.form.get('keep_old_images', 'false').lower() == 'true'
        old_images = data["userList"][idx]["imgurl"].split(',') if keep_old else []
        final_images = [img for img in old_images if img.strip()] + new_images

        # 更新参与者
        updated = {"name": new_name, "imgurl": ",".join(final_images)}
        data["userList"][idx] = updated
        if data["lastWinner"] and data["lastWinner"]["name"] == name:
            data["lastWinner"] = updated

        if save_data(data):
            return jsonify({"success": True, "message": "更新成功", "participant": updated})
        else:
            return jsonify({"success": False, "message": "保存数据失败"}), 500

    except Exception as e:
        return jsonify({"success": False, "message": f"服务器错误: {str(e)}"}), 500


@app.route("/clear", methods=['DELETE'])
def clear_participants():
    try:
        data = load_data()
        # 删除所有图片
        for p in data["userList"]:
            if p.get("imgurl"):
                for img in p["imgurl"].split(','):
                    if img.strip():
                        img_path = os.path.join(app.config['UPLOAD_PATH'], img.strip())
                        if os.path.exists(img_path):
                            os.remove(img_path)
        # 清空数据
        data["userList"] = []
        data["lastWinner"] = None
        if save_data(data):
            return jsonify({"success": True, "message": "清空成功"})
        else:
            return jsonify({"success": False, "message": "保存数据失败"}), 500
    except Exception as e:
        return jsonify({"success": False, "message": f"服务器错误: {str(e)}"}), 500


if __name__ == '__main__':
    # 启动时打印上传路径，方便调试
    print(f"静态文件夹路径: {app.static_folder}")
    print(f"图片上传路径: {app.config['UPLOAD_PATH']}")
    app.run(debug=True)